package cn.jbolt.core.service;

import cn.jbolt.core.base.JBoltMsg;
import cn.jbolt.core.common.enums.JBoltSystemLogTargetType;
import cn.jbolt.core.db.sql.Sql;
import cn.jbolt.core.model.SensitiveWord;
import cn.jbolt.core.sensitiveword.JBoltSensitiveWordUtil;
import cn.jbolt.core.service.base.JBoltBaseService;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;

import java.util.List;


/**
 * 敏感词词库service
 *
 * @ClassName: JBoltSensitiveWordService
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2020年5月2日
 */
public class JBoltSensitiveWordService extends JBoltBaseService<SensitiveWord> {
	protected SensitiveWord dao = new SensitiveWord().dao();

	@Override
	protected SensitiveWord dao() {
		return dao;
	}

	/**
	 * 获取所有String
	 *
	 * @return
	 */
	public List<String> getAllEnableWords() {
		return query(selectSql().select("content").eq("enable",TRUE));
	}

	/**
	 * 分页查询后台管理数据
	 * @param pageNumber
	 * @param pageSize
	 * @param keywords
	 * @param enable
	 * @return
	 */
	public Page<SensitiveWord> paginateAdminDatas(int pageNumber,int pageSize,String keywords,Boolean enable){
		Sql sql = selectSql().page(pageNumber,pageSize);
		sql.like("content",keywords);
		sql.eqBooleanToChar("enable",enable);
		return paginate(sql);
	}


	/**
	 * 保存
	 * @param sensitiveWord
	 * @return
	 */
	public Ret save(SensitiveWord sensitiveWord) {
		if(sensitiveWord==null||isOk(sensitiveWord.getId())||notOk(sensitiveWord.getContent())) {
			return fail(JBoltMsg.PARAM_ERROR);
		}
		if(exists("content",sensitiveWord.getContent())) {return fail(JBoltMsg.DATA_SAME_NAME_EXIST);}
		sensitiveWord.setEnable(true);
		boolean success=sensitiveWord.save();
		if(success){
			JBoltSensitiveWordUtil.me.reload();
		}
		return ret(success);
	}

	/**
	 * 更新
	 * @param sensitiveWord
	 * @return
	 */
	public Ret update(SensitiveWord sensitiveWord) {
		if(sensitiveWord==null||notOk(sensitiveWord.getId())||notOk(sensitiveWord.getContent())) {
			return fail(JBoltMsg.PARAM_ERROR);
		}
		if(!existsById(sensitiveWord.getId())) {return fail(JBoltMsg.DATA_NOT_EXIST);}
		if(exists("content",sensitiveWord.getContent(), sensitiveWord.getId())) {return fail(JBoltMsg.DATA_SAME_NAME_EXIST);}
		boolean success=sensitiveWord.update();
		if(success){
			JBoltSensitiveWordUtil.me.reload();
		}
		return ret(success);
	}

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public Ret delete(Long id){
		Ret ret = deleteById(id);
		if(ret.isOk()){
			JBoltSensitiveWordUtil.me.reload();
		}
		return ret;
	}

	@Override
	protected String afterDeleteByIds(Object[] ids) {
		JBoltSensitiveWordUtil.me.reload();
		return null;
	}

	@Override
	protected String afterToggleBoolean(SensitiveWord model, String column, Kv kv) {
		if(column.toLowerCase().equals(ENABLE)){
			JBoltSensitiveWordUtil.me.reload();
		}
		return null;
	}

	@Override
	protected int systemLogTargetType() {
		return  JBoltSystemLogTargetType.NONE.getValue();
	}

}
